<?php
/**
 * Parcl
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://parcl.com/license
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@parcl.com so we can send you a copy immediately.
 *
 * @category parcl
 * @package parcl-core
 * @copyright Copyright (c) 2006-2011 Mikael Knutsson (http://mikn.me)
 * @license http://parcl.com/license New BSD License
 */
namespace Parcl\Core {

	if(PARCL_EXEC !== 1) {
		die('<h1>Incorrect Access</h1>You cannot access this file directly.<br/>' .
			'If you got this error message by clicking a link on the site, ' .
			'please notify the webmaster as soon as possible.');
	}

	/**
	 * The class which is responsible for autoloading the modules. It also checks
	 * for query classes. It is responsible for the lazy loading parcl uses.
	 * @uses ScanModules To do the actual scanning.
	 * @uses Registry To store the results of the scan so that it doesn't have to
	 * be a singleton.
	 * @todo Might be questionable to load the modules in the registry, and the query modules here. They should probably be loaded in the same place.
	 */

	class Modules extends Events {

		public function __construct() {
			parent::__construct();
			$registry = Registry::GetInstance();
			$scanModules = $registry->Get('ScanModules');
			$registry->Register('QueryModules', $scanModules->ScanFor('queries'));
		}
		public function AutoloadModules($className) {
			$registry = Registry::GetInstance();
			// Passing $className without reference since we don't want runtime changes.
			$this->triggerEvent('P:MODULE_LOADING', array('className' => $className));
			// Is it a query being requested instead of a module?
			// Do we know about that the module is supposed to have queries?
			if(($place = mb_strpos($className, 'Queries')) !== false && in_array($moduleName = mb_substr($className, 0, $place), $registry->Get('QueryModules'))) {
				// Load the query class file for the module.
				include_once MODULE_DIR . strtolower($moduleName) . '/queries/' . $registry->conf->dbType . '.php';
			}
			// If it's not a query class, then is it a known module being loaded?
			elseif(in_array($className = strtolower($className), $registry->Get('modules'))) {
				include_once MODULE_DIR . $className . '/' . $className . '.php';
			}
			// Otherwise, throw an error.
			else {
				throw new GeneralException('The class ' . $className . ' is not a module. ' .
									   'Please fix!', GeneralException::MODULES);
			}
		}
	}
}